package com.zretc.point.service;

import com.zretc.api.pojo.Commodity;
import com.zretc.api.pojo.Pager;
import com.zretc.api.pojo.Point;
import com.zretc.api.pojo.User;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.point.common.constant.CommodityConstant;
import com.zretc.point.common.constant.PointConstant;
import com.zretc.point.dao.CommodityMapper;
import com.zretc.point.dao.PointMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class CommodityService {
    @Resource
    private CommodityMapper commodityMapper;

    @Resource
    private PointMapper pointMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    public Commodity getCommodityById(Integer comId){
        return commodityMapper.getCommodityById(comId);
    }

    /*
     * 对全部商品进行分页查询
     */
    public Map<String, Object> queryCommodity(Integer pageNum, Integer pageSize){
//        pageNum = (pageNum - 1) * pageSize;
        int total = commodityMapper.getAllCommodity().size();
        Pager pager = new Pager(total, pageNum, pageSize);
        ArrayList<Commodity> commoditiesThisPage = commodityMapper.getPageCommodity(pager.getStartIndex(), pageSize);

        Map<String, Object> res = new HashMap<>();
        res.put("list", commoditiesThisPage);
        res.put("pager", pager);
        return res;
    }

    /*
     * 对在售商品进行分页查询
     */
    public Map<String, Object> queryCommodityOnSale(Integer pageNum, Integer pageSize, String comName){
//        pageNum = (pageNum - 1) * pageSize;
        int total = commodityMapper.getCommodityOnSale().size();
        Pager pager = new Pager(total, pageNum, pageSize);
        ArrayList<Commodity> commoditiesOnSaleThisPage = commodityMapper.getPageCommodityOnSale(pager.getStartIndex(), pageSize, comName);
        Map<String, Object> res = new HashMap<>();
        res.put("list", commoditiesOnSaleThisPage);
        res.put("pager", pager);
        return res;
    }

    /*
     * 新增商品
     */
    public RespResult addCommodity(Commodity commodity){

        if(Objects.isNull(commodity.getReputation()) || Objects.isNull(commodity.getPrice()))
        {
            return R.fail(WebConstant.ADD_COMMODITY_ERROR_CODE, WebConstant.ERROR_302);
        }
        else if (!(commodity.getPrice() > 0)) {
            return R.fail(WebConstant.PRICE_COMMODITY_ERROR_CODE, WebConstant.ERROR_304);
        }
        else if(!(commodity.getReputation() > 0))
        {
            return R.fail(WebConstant.REPUTATION_COMMODITY_ERROR_CODE, WebConstant.ERROR_305);
        }
        else {
            StringBuilder commodityName = new StringBuilder("声望*");
            commodityName.append(Integer.toString(commodity.getReputation()));
            commodity.setComName(commodityName.toString());

            if (Objects.isNull(commodity.getComIntroduce())) {
                commodity.setComIntroduce(CommodityConstant.DEFAULT_INTRODUCTION);
            }
            commodityMapper.addCommodity(commodity);

            System.out.println(commodity); // test

            return R.success("新增成功");
        }
    }

    /*
     * 逻辑删除
     */
    public RespResult deleteCommodity(Integer comId){

        if(Objects.isNull(comId))
        {
            return R.fail(404, WebConstant.ERROR_404);
        }
        Commodity commodity = commodityMapper.getCommodityById(comId);
        if(commodity.getComIsDelete() == 1)
        {
            return R.fail(WebConstant.DELETE_COMMODITY_ERROR_CODE, WebConstant.ERROR_306);
        }
        else
        {
            commodityMapper.deleteCommodityById(commodity);
            return R.success("删除成功");
        }
    }

    /*
     * 逻辑恢复
     */
    public RespResult restoreCommodity(Integer comId){
        if(Objects.isNull(comId))
        {
            return R.fail(404, WebConstant.ERROR_404);
        }
        Commodity commodity = commodityMapper.getCommodityById(comId);

        if(commodity.getComIsDelete() == 0)
        {
            return R.fail(WebConstant.RESTORE_COMMODITY_ERROR_CODE, WebConstant.ERROR_307);
        }
        else
        {
            commodityMapper.restoreCommodityById(commodity);
            return R.success("恢复成功");
        }
    }

    /*
     * 购买商品
     */
    public RespResult buyCommodity(Integer comId ,Integer userId){

        //System.out.println("CommodityService================================================================="); // test

        if(Objects.isNull(comId) || Objects.isNull(userId))
        {
            return R.fail(404, WebConstant.ERROR_404);
        }

        Commodity commodity = commodityMapper.getCommodityById(comId);
        User buyer = userFeignClient.getUserInfoById(userId);

//        System.out.println(commodity);
//        System.out.println(buyer);

        if(commodity.getComIsDelete() == 1)
        {
            return R.fail(WebConstant.BUY_COMMODITY_ERROR_CODE_2, WebConstant.ERROR_308);
        }
        else if(buyer.getPoint() < commodity.getPrice())
        {
            return R.fail(WebConstant.BUY_COMMODITY_ERROR_CODE, WebConstant.ERROR_303);
        }
        else
        {
            buyer.setPoint(buyer.getPoint() - commodity.getPrice());
            buyer.setReputation(buyer.getReputation() + commodity.getReputation());

            Point point = new Point();
            point.setUserId(buyer.getUserId());
            StringBuilder pointAction = new StringBuilder(PointConstant.Action_Buy).append(commodity.getComName());
            point.setUserAction(pointAction.toString());
            point.setVariation(-commodity.getPrice());
            point.setCreatedTime(new Timestamp(System.currentTimeMillis()));

//            System.out.println("--  --  --  --  --  --  --  --  --  --");
//            System.out.println(buyer);
//            System.out.println(point);

            pointMapper.addPointAction(point);
            return userFeignClient.updatePointOrReputation(buyer);
        }
    }

}
